package org.yx.service.smfr.view_material_sn_can_input_work_order;

import com.xiaoleilu.hutool.collection.CollUtil;
import org.yx.exception.BizException;
import org.yx.models.SbasMatDef;
import org.yx.service.smat.view_material_sn.MatMsn;
import org.yx.service.smat.view_material_sn.SmatViewMaterialSnIn;
import org.yx.service.smat.view_material_sn.SmatViewMaterialSnService;
import org.yx.service.smfr.view_work_order_need_input_material.SmfrViewWorkOrderNeedInputMaterialIn;
import org.yx.service.smfr.view_work_order_need_input_material.SmfrViewWorkOrderNeedInputMaterialService;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;
import org.yx.utils.ServiceBeanUtil;

import java.util.List;

/**
 * 查询物料批次条码是否能投入工单中
 *
 * @author zxw
 * @since 2023/03/23
 **/
public class SmfrViewMaterialSnCanInputWorkOrderService extends BaseService {
    public SmfrViewMaterialSnCanInputWorkOrderOut viewMaterialSnCanInputWorkOrder(SmfrViewMaterialSnCanInputWorkOrderIn in) throws Exception {
        checkStringNotBlank(in, "mo,msn");

        SmatViewMaterialSnIn snIn = new SmatViewMaterialSnIn();
        snIn.setMsn(in.getMsn());
        List<MatMsn> msnList = ServiceBeanUtil.getBean(SmatViewMaterialSnService.class).viewMaterialSn(snIn).getMsnList();

        MatMsn msnSts = CollUtil.isEmpty(msnList) ? null : msnList.get(0);
        if (msnSts == null || "D".equals(msnSts.getStatus())) {
            throw new BizException("SMAT-0005", "物料批号${msn}不存在或已经被删除。", FieldMap.of("msn", in.getMsn()));
        }

        if (!"P".equals(msnSts.getStatus())) {
            throw new BizException("SMAT-0014", "物料批号${msn}当前不是生产状态。", FieldMap.of("msn", msnSts.getMsn()));
        }

        if (!in.getMo().equals(msnSts.getMo())) {
            //TODO 是否能允许跨工单用料
        }

        if (in.getInputQty() != null && in.getInputQty().compareTo(msnSts.getQty()) > 0) {
            throw new BizException("SMFR-0019", "用量不正确，物料批次${msn}当前数量${qty}。",
                    FieldMap.of("msn", msnSts.getMsn()), FieldMap.of("qty", msnSts.getQty()));
        }

        SmfrViewWorkOrderNeedInputMaterialIn needInputIn = new SmfrViewWorkOrderNeedInputMaterialIn();
        needInputIn.setMo(in.getMo());
        needInputIn.setMatCode(msnSts.getMatCode());
        needInputIn.setMatVer(msnSts.getMatVer());
        List<SbasMatDef> matDefList = ServiceBeanUtil.getBean(SmfrViewWorkOrderNeedInputMaterialService.class).viewWorkOrderNeedInputMaterial(needInputIn).getMatList();
        if (CollUtil.isEmpty(matDefList)) {
            throw new BizException("SMFR-0018", "物料批次${msn}物料${matCode}不在工单${mo}的BOM中。",
                    FieldMap.of("msn", msnSts.getMsn()), FieldMap.of("matCode", msnSts.getMatCode()), FieldMap.of("mo", in.getMo()));
        }

        SmfrViewMaterialSnCanInputWorkOrderOut out = new SmfrViewMaterialSnCanInputWorkOrderOut();
        out.setMsnSts(msnSts);

        return out;
    }
}